package cn.itheima.web;

import cn.itheima.domain.Section;
import cn.itheima.domain.User;
import cn.itheima.service.UserService;
import cn.itheima.service.UserServiceImp;
import cn.itheima.utils.CommonsUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @author: cuisensen
 * data: 2018/7/5.
 * time: 8:34.
 */
@WebServlet("/addUser")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        User user=new User();
        HttpSession session = request.getSession();
        try {
            BeanUtils.populate(user,request.getParameterMap());
            String isFlag = request.getParameter("isFlag");
            UserService us=new UserServiceImp();

            if (isFlag!=null&&!"".equals(isFlag)){
                user.setStartDate(new Date().toLocaleString());
                user.setUid(CommonsUtils.getUUID());
                user.setCode(((User)session.getAttribute("user")).getCode());
                List<Section> sections = (List<Section>) session.getAttribute("sections");
                for (Section s:sections){
                    if(s.getSid()==user.getSid()){
                        if (s.getSname().equals("人事部")){
                            user.setUpassword("123456");
                        }
                    }
                }
                if(user.getRoot()==2){
                    user.setUpassword("123456");
                }
                us.insertUser(user);
            }else {
                User u=(User) session.getAttribute("user");
                user.setUid(u.getUid());
                user.setUpassword(u.getUpassword());
                user.setCode(u.getCode());
                user.setBirthday(u.getBirthday());
                user.setCompanyName(u.getCompanyName());
                us.updateUser(user);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        session.setAttribute("includePage","addSuccess.jsp");
        request.getRequestDispatcher(request.getContextPath()+"/index.jsp").forward(request,response);
    }
}
